package com.test.ch01;

import java.util.Arrays;

public class AllSort {
    public static void main(String[] args) {
        int[] arr=new int[]{10,9,8,7,6,5,4,3,2,1};
        int[] arr1=new int[10];
        System.arraycopy(arr,0,arr1,0,arr.length);
        //System.out.println(Arrays.toString(arr1));
        bubbleSort(arr);
        System.out.println("bubbleSort:"+ Arrays.toString(arr));
        selectSort(arr1);
        System.out.println("SelectSort:"+Arrays.toString(arr1));
        int[] arr2=new int[]{10,9,8,7,6,5,4,3,2,1};
        insertSort(arr2);
        System.out.println("insertSort:"+Arrays.toString(arr2));
    }
    public static void insertSort(int... arr){
        int temp=0;
        for (int i = 1; i < arr.length; i++) {
            temp=arr[i];
            int j = i-1;
            for (; j>=0 ; j--) {
                if(temp>arr[j])
                {
                    break;
                }else{
                    arr[j+1]=arr[j];
                }
            }
            arr[j+1]=temp;
        }
    }
    public static void selectSort(int... arr){
        int min=0;
        int temp=0;
        for (int i = 0; i < arr.length-1; i++) {
            //每次将i给min
            min=i;
            for (int j = i+1; j < arr.length; j++) {
                if(arr[j]<arr[min]){
                    min=j;
                    temp=1;
                }
            }
            //考虑到不相等在交换，否则会出现0
            if(min!=i){
                arr[min]=arr[i]^arr[min];
                arr[i]=arr[i]^arr[min];
                arr[min]=arr[i]^arr[min];
            }


            if(temp==0){
                break;
            }
        }
    }
    public static void bubbleSort(int... arr){
       int temp=0;
        for (int i = 0; i < arr.length-1; i++) {

            for (int j = 0; j < arr.length-1-i; j++) {
                if(arr[j]>arr[j+1]){
                    arr[j]=arr[j]^arr[j+1];
                    arr[j+1]=arr[j]^arr[j+1];
                    arr[j]=arr[j]^arr[j+1];
                    temp=1;
                }

            }
            if(temp==0){
                break;
            }
        }
    }
}
